<?php

class GDGE_Security
{
	private static $_instance = null;
	
	/**
	 * Singleton pattern
	 * @return GDGE_Security
	 */
	public static function getInstance()
	{
		if (self::$_instance == null) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}
	
	private function __construct() { }
	private function __clone() { }
	
	/**
	 * 
	 * @var Zend_Session_Namespace
	 */
	private $_session = null;
	
	/**
	 * Returns session namespace for security
	 * @return Zend_Session_Namespace
	 */
	private function getSession()
	{
		if ($this->_session == null) {
			$this->_session = new Zend_Session_Namespace('GDGE_Security', true);
		}
		return $this->_session;
	}
	
	private $isValidated = false;
	
	/**
	 * 
	 * Authenticate a user
	 * @param GDGE_Auth_Adapter_Interface $adapter
	 * @return GDGE_Auth_Result
	 */
	public function authenticate(GDGE_Auth_Adapter_Interface $adapter, $username, $password)
	{
		$result = $adapter->authenticate($username, $password);
		$session = $this->getSession();
		if (!$result->isValid()) {
			Zend_Session::destroy();
			return $result;
		}
		$session->login = true;
		$session->id = $result->getIdentity();
		$this->isValidated = true;
		return $result;
	}
	
	/**
	 * 
	 * Returns true if there is a logged in user
	 * @param GDGE_Auth_Adapter_Interface $adapter
	 * @return boolean true on successful validation
	 */
	public function validate(GDGE_Auth_Adapter_Interface $adapter)
	{
		$session = $this->getSession();
		if ($session->login == true) {
			$id = $session->id;
			if (!$adapter->validate($id)) {
				Zend_Session::destroy();
				$this->isValidated = false;
				return false;
			}
			$this->isValidated = true;
			return true;
		}
	}
	
	/**
	 * Logout current user
	 */
	public function logout()
	{
		$this->isValidated = false;
		Zend_Session::destroy();
	}
	
	/**
	 * Get the identity of the user logged in
	 * @return int|string
	 */
	public function getIdentity()
	{
		if (!$this->isValidated) throw new Exception("Not validated.");
		$session = $this->getSession();
		if (!$session->login) throw new Exception("No user logged in!");
		return $session->id;
	}
	
}